//
//  BPAppearWeiboControl.swift
//  BPWeiBo
//
//  Created by 扒皮大叔 on 16/4/14.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import SVProgressHUD
import SnapKit
class BPAppearWeiboControl: UIViewController,UITextViewDelegate {
    var cBtn = UIButton()
    private lazy var picVc:BPPicWeiBoControl = BPPicWeiBoControl()
    
    var imgList:Int = 0{
        didSet{
            if imgList > 0{
            navigationItem.rightBarButtonItem?.enabled = true
            }else {
            navigationItem.rightBarButtonItem?.enabled = false

            }
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = BapiColor
        setNav()
        setUpUI()
        setToolBar()
        creatNotifation()
        //将toolbar 移到最顶层
        view.bringSubviewToFront(toolBar1)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    //MARK:懒加载textView
//    private lazy var textView:UITextView = {
//        let text = UITextView()
//        text.keyboardDismissMode = .OnDrag
//        text.font = UIFont.systemFontOfSize(18)
//        text.textColor = UIColor.blackColor()
//        text.backgroundColor = UIColor(white: 0.95,alpha: 1)
//        text.alwaysBounceVertical = true
//        text.delegate = self
//        
//        return text
//    }()
    
    
    private lazy var textView: HMEmoticonTextView = {
        let tv = HMEmoticonTextView()
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.darkGrayColor()
        tv.backgroundColor = UIColor(white: 0.95,alpha: 1)
        tv.alwaysBounceVertical = true
        //        tv.delegate = self
        tv.keyboardDismissMode = .OnDrag
        //设置代理
        tv.delegate = self
        return tv
    }()
    
    
    //MARK:设置占位文本
    private lazy var zhnaweiLbl:UILabel = UILabel(text: "听说下雨天音乐和辣条更配哦...", textColor: UIColor.grayColor(), fontSize: 14)
    
    private lazy var toolBar1:UIToolbar = UIToolbar()
    
    //移除通知观察者观察者
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //自定义键盘视图
    private lazy var keyboardView: HMEmoticonKeyboardView = HMEmoticonKeyboardView()
    
    @objc private func insertEmoticonText(n: NSNotification) {
        print(n)
        //处理用户点击事件
        guard let em = n.object as? HMEmoticon else {
            print("噢 出大事啦")
            return
        }
        textView.insertEmotioncText(em)
    }

    
}


//MARK:----------------------------------------------------------------
//MARK:设置底部的toolBar
extension BPAppearWeiboControl {
    
    private func setToolBar() {
        //首先创建按钮
        //图片按钮
        let picItem = UIBarButtonItem(imgName: "compose_toolbar_picture", title: String(), target: self, action: "sendPic")
        //@按钮
        let altItem = UIBarButtonItem(imgName: "compose_mentionbutton_background", title: String(), target: self, action: "sendAlt")
        //#号按钮
        let jinItem = UIBarButtonItem(imgName: "compose_trendbutton_background", title: String(), target: self, action: "sendJin")
        //表情按钮
        let enjoinItem = UIBarButtonItem(imgName: "compose_emoticonbutton_background", title: String(), target: self, action: "sendEnjoin")
        //添加按钮
        let addItem = UIBarButtonItem(imgName: "compose_add_background", title: String(), target: self, action: "sendAdd")
        //创建弹簧
        let tanItem = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
        //创建toolbar
        //var toolBar = UIToolbar()
        
        //设置toolbar的背景色
        toolBar1.barTintColor = UIColor.lightGrayColor()
        
        //把所有的item添加到toolbar上面
        toolBar1.items = [tanItem,picItem,tanItem,altItem,tanItem,jinItem,tanItem,enjoinItem,tanItem,addItem,tanItem]

        //设置item宽
        picItem.width = ScreenWidth / 5
        addItem.width = picItem.width
        enjoinItem.width = picItem.width
        altItem.width = picItem.width
        jinItem.width = picItem.width
        

    }
    
    //每个按钮实现的方法
    //发送图片
    @objc private func sendPic() {
       self.picVc.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo((ScreenHeight / 3)*2)
        }
        //navigationItem.rightBarButtonItem?.enabled = true
        
    }
    //发送@
    @objc private func sendAlt() {
    
    }
    //发送#话题
    @objc private func sendJin() {}
    //发送表情
    @objc private func sendEnjoin() {
        //选择表情
        textView.inputView = (keyboardView.inputView == nil ? keyboardView : nil)
        //刷新inputview
        textView.reloadInputViews()
        
        //如果不是第一响应者 就成为第一响应者
        if !textView.isFirstResponder() {
            
            textView.becomeFirstResponder()
        }
    }
    //添加更多
    @objc private func sendAdd() {}


}


//MARK:----------------------------------------------------------------
//MARK:建立通知,通过键盘的通知来改变我们toolbar的约束
extension BPAppearWeiboControl {
    //注册通知
    private func creatNotifation() {
    
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    
    //注册表情键盘的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "insertEmoticonText:", name: HMEmoticonBtnDidClick, object: nil)
    }
    
    //实现通知的方法
    @objc private func keyBoardWillChangeFrame(n:NSNotification) {
        //获取通知的文本
        let userInfo = n.userInfo
        //通过文本来获取键盘的frame
        let rect = (userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        //获取键盘的y值
        let keyBoardH = -ScreenHeight + rect.origin.y
        
        //设置toolzar的约束
        self.toolBar1.snp_updateConstraints(closure: { (make) in
            make.bottom.equalTo(keyBoardH)
        })
        //强制刷新
        UIView.animateWithDuration(1.0) {
            self.view.layoutIfNeeded()
        }

    }


}


//MARK:----------------------------------------------------------------

//MARK:点击取消和发送按钮的方法
extension BPAppearWeiboControl {
    @objc private func send() {
        //print("OK")
        //执行发送微博的请求
        let text:String = self.textView.showFullText()
        guard let token = BPUserInfoViewModel.sharedUserInfoViewModel.userInfo?.access_token else {
            
            SVProgressHUD.showErrorWithStatus("你没有登录")
            return
        }
        BPAFNetworkingTool.sharedTools.sendWeiBo(token, status: text,imgList: picVc.selectedimg) { (respondData, error) in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("数据解析错误")
                print(error)
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("微博发布成功")
            UIView.animateWithDuration(1.0, animations: {
                self.dismissViewControllerAnimated(true, completion: nil)

            })
        }
        
    }
    @objc private func cancle() {
        dismissViewControllerAnimated(true, completion: nil)
        //取消第一响应者
        textView.resignFirstResponder()
    }

}


//MARK:----------------------------------------------------------------

//MARK:textVIew的代理方法
extension BPAppearWeiboControl {
    //MARK:textView的代理方法
    func textViewDidChange(textView: UITextView) {
        //设置按钮可以交互
        if textView.hasText() {
            navigationItem.rightBarButtonItem?.enabled = true
        }else {
            navigationItem.rightBarButtonItem?.enabled = false
            
        }
    }
    func textViewDidBeginEditing(textView: UITextView) {
        //隐藏占位文本
        zhnaweiLbl.hidden = true
        
        imgList = self.picVc.selectedimg.count
    }
    func textViewDidEndEditing(textView: UITextView) {
        if !textView.hasText() {
        zhnaweiLbl.hidden = false
        }else {
        zhnaweiLbl.hidden = true

        }
    }
    
    //MARK:点击屏幕的时候让键盘缩回去
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        //取消第一响应者
        textView.resignFirstResponder()
    }

}


//MARK:----------------------------------------------------------------

//MARK:设置UI
extension BPAppearWeiboControl {
    
    private func setBtn1() -> UIButton {
        
        let btn = UIButton(type: .Custom)
        btn.setTitle("发送", forState: .Normal)
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitle("发送", forState: .Disabled)
        btn.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        btn.titleLabel?.font = UIFont.systemFontOfSize(14)
        btn.frame = CGRect(x: 0, y: 0, width: 45, height: 30)
        btn.addTarget(self, action: "send", forControlEvents: .TouchUpInside)
        
        return btn
    }
    
    private func setNav() {
        
        cBtn = setBtn1()
        
        let rightItem:UIBarButtonItem = UIBarButtonItem(customView: cBtn)
        navigationItem.rightBarButtonItem = rightItem
        navigationItem.rightBarButtonItem?.enabled = false
        let leftItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action:
            "cancle" )
        /*
        Bordered
        */
        leftItem.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.darkGrayColor()], forState: .Normal)
        leftItem.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.orangeColor()], forState: .Highlighted)
        leftItem
        navigationItem.leftBarButtonItem = leftItem
        
        self.title = BPUserInfoViewModel.sharedUserInfoViewModel.userInfo?.name

        navigationItem.prompt = "发布微博"
    }
    
    //MARK:设置UI
    private func setUpUI() {
        

        //添加到view上面
        view.addSubview(toolBar1)
        view.addSubview(textView)
        zhnaweiLbl.textAlignment = .Left
        textView.addSubview(zhnaweiLbl)
        
        self.addChildViewController(self.picVc)
//        cells1 = picVc.cells
        view.addSubview(self.picVc.view)
        //设置约束
        self.textView.snp_makeConstraints { (make) in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(ScreenHeight / 3)
        }
        self.zhnaweiLbl.snp_makeConstraints { (make) in
            make.top.equalTo(textView).offset(10)
            make.left.equalTo(textView).offset(10)
            make.width.equalTo(ScreenWidth)
            //make.height.equalTo(20)
        }
        self.toolBar1.snp_makeConstraints(closure: { (make) in
            make.bottom.equalTo(view)
            make.width.equalTo(ScreenWidth)
        })
        self.picVc.view.snp_makeConstraints(closure: { (make) -> Void in
            make.height.equalTo(0)
            make.left.right.bottom.equalTo(self.view)
        })
    }
    

}
